package com.hdc.lw.service;

import com.hdc.lw.config.RedisPrefix;
import com.hdc.lw.mapper.UserMapper;
import com.hdc.lw.po.LoggedWeekStatistics;
import com.hdc.lw.po.RegisterWeekStatistics;
import com.hdc.lw.po.Response;
import com.hdc.lw.po.User;
import com.hdc.lw.utils.SMSUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.Stream;


@Service
public class UserServiceImpl implements UserServie{

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;    // redis对象

    @Override
    public Object getUserByName(User u){
        Response response = null;
        User user = userMapper.getUserByName(u.getUsername());
        if(user==null){
            response = new Response(Response.COMMON_EXIST,"用户不存在！",null);
        }else if(user.getPassword().equals(u.getPassword())){
            user.setPassword("");
            response = new Response(Response.COMMON_SUCCESS,"登录成功！",user);
            user.setLastLoginTime(new Date());
            userMapper.updateUser(user);
        }else {
            response = new Response(Response.COMMON_FAIL,"密码错误！",null);
        }
        return response;//密码错误
    }

    @Override
    public Object registerUser(User user){
        Response response = null;
        Map<String,Object> map = new HashMap<>();
        User u = userMapper.getUserByName(user.getUsername());
        if(u==null){
            int row = userMapper.registerUser(user);
            if(row>0){
                response = new Response(Response.COMMON_SUCCESS,"注册成功，请继续登录！",null);
            }else {
                response = new Response(Response.COMMON_FAIL,"注册失败！",null);
            }
        }else {
            response = new Response(Response.COMMON_EXIST,"用户名存在，请更换用户名！",null);
        }
        return response;
    }

    /**
     * 发送手机验证码
     * @param phone
     * @return
     */
    @Override
    public Object sendCode(String phone) {
        Response response = new Response();
        // 判断手机号在60s内是否发送过短信
        if (stringRedisTemplate.hasKey(phone + RedisPrefix.THROTTLE)) {
            response = new Response(Response.COMMON_EXIST,"您已经在60s内发送过短信，请稍后重试~",null);
        }else {
            try {
                String code = RandomStringUtils.randomNumeric(6);
//                System.out.println("code = " + code);
                // 调用封装好的发送验证码的工具类进行短信发送
                SMSUtils.sendMsg(phone, code);

                // 将验证码保存到redis中
                stringRedisTemplate.opsForValue().set(phone + RedisPrefix.THROTTLE, code, 60, TimeUnit.SECONDS);  //发送频率限制
                stringRedisTemplate.opsForValue().set(phone + RedisPrefix.OUT, code, 30, TimeUnit.MINUTES);    // 验证码存活时间
                response = new Response(Response.COMMON_SUCCESS,"验证码发送成功！",null);
            } catch (Exception e) {
                response = new Response(Response.COMMON_FAIL,"短信发送异常！",null);
            }
        }
        return response;
    }

    /**
     * 根据手机号登录
     * @param phone 手机号
     * @param code 验证码
     * @return
     */
    @Override
    public Object findUserByPhone(String phone, String code){
        Response response = null;
        Map<String,Object> map = new HashMap<>();
        Map<String,Object> data = new HashMap<>();
        // 通过手机号获取该手机号对应的验证码
        String redisCode = stringRedisTemplate.opsForValue().get(phone + RedisPrefix.OUT);
        // 判断redis中保存的验证码是否与用户输入的验证码一致
        if (redisCode!=null & code.equals(redisCode)){
            // 调用服务  完成登录
            User user = userMapper.findUserByPhone(phone);
            if (user.getId()!=null){
                user.setPassword("");
                user.setLastLoginTime(new Date());
                userMapper.updateUser(user);
                response = new Response(Response.COMMON_SUCCESS,"登录成功！",user);
            }else {
                response = new Response(Response.COMMON_EXIST,"您输入的用户不存在！",user);
            }
        }else {
            response = new Response(Response.COMMON_FAIL,"您输入的验证码不正确！",null);
        }
        return response;
    }

    /**
     * 获取用户列表
     * @param page 获取的页数
     * @param rows 每页用户的条数
     * @param name 迷糊匹配用户名
     * @return
     */
    @Override
    public Object findAllUsers(Integer page, Integer rows, String name) {
        Response response = null;
        int start = (page - 1) * rows;
        // 分页查询每页的对象
        List<User> allUsers = userMapper.findAllUsers(start, rows, name);
        // 获取用户的总数量
        Integer userTotal = userMapper.findUserTotal(name);
        if(allUsers != null && userTotal !=null){
            Map data = new HashMap();
            data.put("users",allUsers);
            data.put("total", userTotal);
            response = new Response(Response.COMMON_SUCCESS, "请求成功！", data);
        }else {
            response = new Response(Response.COMMON_FAIL, "获取数据失败！",null);
        }
        return response;
    }


    /**
     * 统计一周内用户注册数量
     * @return
     */
    @Override
    public Object registerWeek() {
        List<RegisterWeekStatistics> registerWeekStatistics = userMapper.registerWeek();
        return new Response(Response.COMMON_SUCCESS,"获取成功",getStringListMap(registerWeekStatistics.stream().map(RegisterWeekStatistics::getName), registerWeekStatistics.stream().map(RegisterWeekStatistics::getCounts)));
    }

    /**
     * 统计近7天登录情况
     * @return
     */
    @Override
    public Object loggerWeek() {
        List<LoggedWeekStatistics> loggerWeekStatistics = userMapper.loggedWeek();
        return new Response(Response.COMMON_SUCCESS,"获取成功",getStringListMap(loggerWeekStatistics.stream().map(LoggedWeekStatistics::getName), loggerWeekStatistics.stream().map(LoggedWeekStatistics::getCounts)));
    }

    /**
     * 统计手机绑定数
     * @return
     */
    @Override
    public Object getPhone() {
        Map hashMap1 = new HashMap();
        Map hashMap2 = new HashMap();
        List list = new ArrayList();
        hashMap1.put("value",userMapper.bindingPhone());
        hashMap1.put("name","已绑定");
        list.add(hashMap1);
        hashMap2.put("value",userMapper.findUserTotal("")-userMapper.bindingPhone());
        hashMap2.put("name","未绑定");
        list.add(hashMap2);
        return new Response(Response.COMMON_SUCCESS,"获取成功",list);
    }

    /**
     * 根据id删除用户信息
     * @param id
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.SUPPORTS)  // 增删改请求需要控制事务
    public Object deleteUserById(Integer id) {
        Response response = new Response();
        Integer row = userMapper.deleteUserById(id);
        if(row>0){
            response =new Response(Response.COMMON_SUCCESS,"删除成功!",null);
        } else {
            response = new Response(Response.COMMON_FAIL, "删除失败", null);
        }
        return response;
    }

    /**
     * 更新用户信息
     * @param user
     * @return
     */
    @Transactional(propagation = Propagation.SUPPORTS)  // 增删改请求需要控制事务
    @Override
    public Object updateUser(User user) {
        Response response = new Response();
        Integer row = userMapper.updateUser(user);
        if(row>0){
            response =new Response(Response.COMMON_SUCCESS,"删除成功!",null);
        } else {
            response = new Response(Response.COMMON_FAIL, "删除失败", null);
        }
        return response;
    }

    @Override
    public Object getUserById(Integer id) {
        Response response = new Response();
        User user = userMapper.getUserById(id);
        if(user!=null){
            response = new Response(Response.COMMON_SUCCESS, "获取成功",user);
        }else{
            response = new Response(Response.COMMON_FAIL, "获取失败",null);
        }
        return response;
    }

    // 用来处理数据方法
    private Map<String, List<?>> getStringListMap(Stream<String> stringStream, Stream<Integer> integerStream) {
        HashMap<String, List<?>> result = new HashMap<>();
        List<String> lable = stringStream.collect(Collectors.toList());
        List<Integer> integers = integerStream.collect(Collectors.toList());
        result.put("lables", lable);
        result.put("counts", integers);
        return result;
    }
}
